import type http from 'http'
import formidable, { errors as formidableErrors } from 'formidable';
import { getStrFamiliarity } from '../libs/strFamiliarity';
import type { BrowserWindow } from 'electron';
const form = formidable({ multiples: false, maxFieldsSize: 1024 * 1024 * 10, encoding: 'utf-8', maxFields: 100000 });




/**
 * 接收APP端发过来的ocr结果
 */
export async function getMobileOcrResult(
  req: http.IncomingMessage,
  res: http.ServerResponse<http.IncomingMessage>,
  win: BrowserWindow
) {
  let [fields, files] = await form.parse(req);

  const endOutPut = (message = "error", code: number = 400, data: any = "") => {
    res.end(JSON.stringify({ message, code, data }))
  }

  let id = fields?.id?.[0]; //App生成的任务id
  let result = fields?.result?.[0]; //APP识别结果

  if (!id) return endOutPut("请传入任务ID")
  if (!result) return endOutPut("请传入识别结果")

  result = result.replace(/\r/g, '');

  let resultList = result.split(`\n`) as string[]; //分割为数组

  const replaceList: { [key: string]: string } = {
    I: '1',
    i: '1',
    l: '1',
    w: 'm',
    n: 'm',
    g: '9',
    t: '7',
    s: '5',
    S: '5',
    M: 'm',
    b: '6',
    B: '8',
    'o': '0',
    'O': '0',
    '(': '1',
    ')': '1',
    '{': '1',
    '}': '1',
    '[': '1',
    ']': '1',
    '（': '1',
    "）": '3',
  }

  /**
   * 相似度阈值 (%)
   */
  const percentageThreshold = 90


  let resList: {
    closestItem: string
    similarityPercent: number
    originalStr: string
    row: string
  }[] = [];

  for (let i = 0; i < resultList.length; i++) {
    let rowItem = String(resultList[i]);

    rowItem = rowItem.replace(/\s+/g, "");

    // 替换易错字符
    Object.keys(replaceList).map(key => {
      key = key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
      rowItem = rowItem.replace(
        new RegExp(key, 'g'),
        replaceList[key],
      )
    })

    let mStart = rowItem.indexOf("m");
    // 文本长度大于13时 截取m后边12个字符进行判断
    if (rowItem.length >= 13 && mStart != -1) {
      let mStr = rowItem.substring(mStart, mStart + 12);
      if (countNumbers(mStr) < 8) {
        continue;
      }
      let rowRes = getStrFamiliarity(mStr);
      if (rowRes.similarityPercent >= percentageThreshold) {
        resList.push({
          originalStr: resultList[i],
          row: mStr,
          ...rowRes,
        })
      }
      continue;
    }


    let numberCount = countNumbers(rowItem);
    if (
      rowItem.length < 8
      || rowItem.length > 16
      || numberCount < 8
      || numberCount > 13
    ) {
      continue;
    } else {
      resList.push({
        originalStr: resultList[i],
        row: rowItem,
        ...getStrFamiliarity(rowItem),
      })
    }
  }

  if (resList.length == 0) {
    res.end(JSON.stringify({ code: 200 }))
    return;
  }

  let lastItem = resList[0];
  resList.map((x, index) => {
    if (index > 0) {
      if (lastItem.similarityPercent < x.similarityPercent) {
        lastItem = x;
      }
    }
  })

  if (lastItem.similarityPercent < percentageThreshold) {
    res.end(JSON.stringify({ code: 200 }))
    return;
  }

  // let checkUserId = lastItem.closestItem.replace(/\D/g, '');
  let checkUserId = lastItem.closestItem;

  win.webContents.send("serverGetUserCodeSuccess", checkUserId)

  console.log(`识别结果: ${checkUserId}       准确率[${lastItem.similarityPercent}%]`);

  res.end(JSON.stringify({ code: 200 }))

}







/**
 * 统计字符串内包含几个数字
 */
function countNumbers(str: string) {
  const matches = str.match(/\d/g); // \d 匹配任何数字字符
  return matches ? matches.length : 0;
}

/**
 * 统计中文出现的字符数量
 */
function countChineseCharacters(str: string) {
  const matched = str.match(/[\u4e00-\u9fff]/g);
  return matched ? matched.length : 0;
}